//
//  ZZHomeLabelView.m
//  Qzone
//
//  Created by zhangxy on 2018/6/12.
//  Copyright © 2018年 zhang. All rights reserved.
//

#import "ZZHomeLabelView.h"
#import "MyButton.h"
#import <SDCycleScrollView.h>
#import "BannerEntity.h"
#import "SVWebViewController.h"
#import "TopicHomeController.h"
#import "TopListController.h"

@interface ZZHomeLabelView()<SDCycleScrollViewDelegate>{
    UIButton *checkBtn;
    MyButton *checkMenuBtn;
    NavTypeEntity *typeEntity;
    CGFloat topTypeHeight;
}
@property(nonatomic,strong)NSMutableArray *headerArr;
@property(nonatomic,strong)UITableView *tableView;

@property(nonatomic,strong)UIView *topView;
@property(nonatomic,strong)UIView *topLabelView;
@property(nonatomic,strong)UIButton *btnArrow;
@property(nonatomic,strong) void (^pComplateBlock)(id tag,NSString *title);

@end

@implementation ZZHomeLabelView


-(id)initWithTable:(UITableView *)listTable result:(void (^)(id, NSString *))complateBlock{
    self = [super initWithFrame:CGRectMake(0, 0, ScreenWidth, 0)];
    if(self){
        self.backgroundColor = UIColorFromRGB(BgTitleColor);
        _pComplateBlock = complateBlock;
        _tableView = listTable;
        
        _topView = [[UIView alloc] initWithFrame:CGRectZero];
        [_topView setBackgroundColor:UIColor.clearColor];
        
        _topLabelView = [[UIView alloc] initWithFrame:CGRectZero];
        [_topView addSubview:_topLabelView];
        
        _topLabelView.hidden = YES;
    }
    return self;
}

-(void) setEntiy:(NavTypeEntity *)entity{
    if(typeEntity!=nil && [typeEntity.nav_id isEqual:entity.nav_id]){
        return;
    }
    typeEntity = entity;
    
    _headerArr = [[NSMutableArray alloc] init];
    
    
    
    _topLabelView.hidden = YES;
    if([entity.nav_name isEqual:@"推荐"]){
        
        [self setFrame:CGRectMake(0, 0, ScreenWidth, 217)];
        
        [self getBannerList];
    }else if([entity.nav_id isEqual:@"0"]){
        
    }else{
        [self addSubview:_topView];
        
        [self getNavTypeList];
    }
}

-(void)hideTopTags{
    if(_topLabelView && !_topLabelView.hidden){
        _topLabelView.hidden = YES;
        
        [self.topView setFrame:CGRectMake(0, 0, ScreenWidth, topTypeHeight)];
        //            [self.bottomView setFrame:CGRectMake(0, topTypeHeight, ScreenWidth, 44)];
        [self setFrame:CGRectMake(0, 0, ScreenWidth, topTypeHeight)];
        [self.tableView beginUpdates];
        [self.tableView setTableHeaderView:self];
        [self.tableView endUpdates];
    }
}




-(void)getNavTypeList{
    
    [NetworkUtil POST:API_GetCatList parameters:@{@"nav_id":typeEntity.nav_id} success:^(id responseObject, NSDictionary *dict) {
        NSArray *arr = dict[@"data"];
        if(arr.count > 0){
            int i = 0;
            CGFloat sx = 7.0f;
            CGFloat y = 14;
            
            CGFloat x = 22;
            for (NSDictionary *item in arr) {
                NavTypeEntity *nav = [[NavTypeEntity alloc] initWithDictionary:item];
                CGRect f = CGRectMake(x, y, 30, 30);
                MyButton *btn = [self createMenuButton:f m:nav];
                CGSize s = [self autoWidthOfLabel:btn.titleLabel with:30];
                
                f.size.width = s.width + 30;
                if(CGRectGetMaxX(f) + 12 > ScreenWidth){
                    y = y + 30 + 10;
                    x = 22;
                }
                f.origin.x = x;
                f.origin.y = y;
                
                x = CGRectGetMaxX(f) + sx;
                
                btn.frame = f;
                [btn setBackgroundColor:UIColorFromRGBAlpha(TextWhiteColor, 0.3)];
                btn.layer.cornerRadius = 8.0f;
                btn.layer.masksToBounds = YES;
                [self.topView addSubview:btn];
                i = i + 1;
            }
            topTypeHeight = y + 30 + 10;
            [self.topView setFrame:CGRectMake(0, 0, ScreenWidth, topTypeHeight)];
//            [self.bottomView setFrame:CGRectMake(0, topTypeHeight, ScreenWidth, 44)];
            [self setFrame:CGRectMake(0, 0, ScreenWidth, y + 40)];
            
            [self.tableView beginUpdates];
            [self.tableView setTableHeaderView:self];
            [self.tableView endUpdates];
        }
    } failure:^(NSError *error, NSString *message) {
        
    }];
}


-(void)getNavTagList:(NavTypeEntity *) catEntity{
    
    [NetworkUtil POST:API_GetTagList parameters:@{@"cat_id":catEntity.cat_id,@"size":@"20"} success:^(id responseObject, NSDictionary *dict) {
        NSArray *arr = dict[@"data"];
        if(arr.count > 0){
            _topLabelView.hidden = NO;
            [_topLabelView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(22, 0, ScreenWidth-44, 44)];
            [label setText:@"标签"];
            [label setFont:FontThirteen];
            [label setTextColor:UIColorFromRGB(TextWhiteColor)];
            [_topLabelView addSubview:label];
            
            int i = 0;
            CGFloat sx = 7.0f;
            CGFloat y = 44;
            
            
            
            CGFloat x = 22;
            for (NSDictionary *item in arr) {
                NavTypeEntity *nav = [[NavTypeEntity alloc] initWithDictionary:item];
                CGRect f = CGRectMake(x, y, 30, 30);
                MyButton *btn = [self createMenuButton:f m:nav];
                [btn setTitle:nav.tag_name forState:0];
                CGSize s = [self autoWidthOfLabel:btn.titleLabel with:30];
            
                f.size.width = s.width + 30;
                if(CGRectGetMaxX(f) + 22 > ScreenWidth){
                    y = y + 30 + 10;
                    x = 22;
                }
                f.origin.x = x;
                f.origin.y = y;
                
                x = CGRectGetMaxX(f) + sx;
                
                btn.frame = f;
                [btn setBackgroundColor:UIColorFromRGBAlpha(TextWhiteColor, 0.3)];
                btn.layer.cornerRadius = 8.0f;
                btn.layer.masksToBounds = YES;
                [self.topLabelView addSubview:btn];
                i = i + 1;
            }
            
            
            self.topLabelView.hidden = NO;
            [self.topLabelView setFrame:CGRectMake(0, topTypeHeight , ScreenWidth, y + 44)];
            
            [self.topView setFrame:CGRectMake(0, 0, ScreenWidth, CGRectGetMaxY(self.topLabelView.frame))];
//            [self.bottomView setFrame:CGRectMake(0, CGRectGetMaxY(self.topLabelView.frame), ScreenWidth, 44)];
            [self setFrame:CGRectMake(0, 0, ScreenWidth, CGRectGetMaxY(self.topLabelView.frame))];
            
            [self.tableView beginUpdates];
            [self.tableView setTableHeaderView:self];
            [self.tableView endUpdates];
        }
    } failure:^(NSError *error, NSString *message) {
        
    }];
}

-(void)getBannerList{
    [NetworkUtil POST:API_Bannerlist parameters:@{} success:^(id responseObject, NSDictionary *dict) {
        NSArray *arr = dict[@"data"];
        for (NSDictionary *item in arr) {
            BannerEntity *model = [[BannerEntity alloc] initWithDictionary:item];
            [self.headerArr addObject:model];
        }
        UIView *view = [self createFirstMenu];
        [self addSubview:view];
    } failure:^(NSError *error, NSString *message) {
        
    }];
}


-(UIView *)createFirstMenu{
    UIView *menuView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 207)];
    [menuView setBackgroundColor:[UIColor clearColor]];
    
    //    UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 130)];
    //    [imgView setBackgroundColor:UIColorFromRGB(BgTitleColor)];
    //    [menuView addSubview:imgView];
    
    SDCycleScrollView *cycleView = [self setupCycleImageCell];
    [menuView addSubview:cycleView];
    
    UIView *itemsView = [[UIView alloc] initWithFrame:CGRectMake(0, 147, ScreenWidth, 50)];
    [itemsView setBackgroundColor:UIColor.whiteColor];
    [menuView addSubview:itemsView];
    
    int i = 1;
    CGFloat cw = (ScreenWidth - 20) / 3;
    for (NSString *item in @[@"排行榜",@"专题",@"商店"]) {
        UIButton *b = [UIButton buttonWithType:UIButtonTypeCustom];
        b.titleLabel.font = FontSeventeen;
        [b setTitleColor:UIColorFromRGB(TextSizeOneColor) forState:0];
        [b setTitle:item forState:0];
        [b setFrame:CGRectMake(10 + (i-1)*cw, 0, cw, 50)];
        b.tag = i;
        [b addTarget:self action:@selector(onTjItemClick:) forControlEvents:UIControlEventTouchUpInside];
        [itemsView addSubview:b];
        i = i+1;
    }
    
    UIImageView *imgView1 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 197, ScreenWidth, 10)];
    [imgView1 setBackgroundColor:UIColorFromRGB(BgSystemColor)];
    [menuView addSubview:imgView1];
    return menuView;
}

/**
 计算Label高度
 
 @param label 要计算的label，设置了值
 @param width label的最大宽度
 */
- (CGSize )autoWidthOfLabel:(UILabel *)label with:(CGFloat )height{
    //Calculate the expected size based on the font and linebreak mode of your label
    // FLT_MAX here simply means no constraint in height
    CGSize maximumLabelSize = CGSizeMake(FLT_MAX, height);
    
    CGSize expectedLabelSize = [label sizeThatFits:maximumLabelSize];
    
    
    return expectedLabelSize;
}

-(MyButton *) createMenuButton:(CGRect) f m:(NavTypeEntity *)entity{
    MyButton *b = [MyButton buttonWithType:UIButtonTypeCustom];
    b.titleLabel.font = FontFiftent;
    [b setTitleColor:UIColorFromRGB(TextWhiteColor) forState:UIControlStateSelected];
    [b setTitleColor:UIColorFromRGBAlpha(TextWhiteColor, 0.6) forState:UIControlStateNormal];
    [b setFrame:f];
    if(entity){
        [b setTitle:entity.cat_name forState:0];
        b.objTag = entity;
    }
    [b addTarget:self action:@selector(onItemClick:) forControlEvents:UIControlEventTouchUpInside];
    return b;
}
-(void)onTjItemClick:(UIButton *) btn{
    if(btn.tag == 1){
        // 排行榜
        TopListController *vc = [[TopListController alloc] init];
        [self.superVC.navigationController pushViewController:vc animated:YES];
    }
    else if(btn.tag == 2){
        // 专题
        TopicHomeController *vc = [[TopicHomeController alloc] init];
        [self.superVC.navigationController pushViewController:vc animated:YES];
    }else{
        // 商店
        
        SVWebViewController *vc = [[SVWebViewController alloc] initWithURL:[NSURL URLWithString:@"https://j.youzan.com/ptOBqY"]];
        [self.superVC.navigationController pushViewController:vc animated:YES];
    }
}

-(void)onItemClick:(MyButton *) btn{
    NavTypeEntity *checkEntity = btn.objTag;
    if([@"menu" isEqual:checkEntity.nav_type]){
        if(checkMenuBtn!=nil){
            checkMenuBtn.selected = NO;
        }
        checkMenuBtn.selected = YES;
        checkMenuBtn = btn;
        
        if(_pComplateBlock){
            _pComplateBlock(checkMenuBtn.objTag,checkMenuBtn.titleLabel.text);
        }
    }else{
        if(checkBtn!=nil){
            checkBtn.selected = NO;
        }
        btn.selected = YES;
        checkBtn = btn;
        
        if(_pComplateBlock){
            _pComplateBlock(btn.objTag,btn.titleLabel.text);
        }
        
        if(convertToString(checkEntity.tag_id).length == 0){
            [self getNavTagList:checkEntity];
        }
    }
}


#pragma mark - 图片轮播
/** 设置轮播图 */
- (SDCycleScrollView  *)setupCycleImageCell
{
    // 网络加载 --- 创建带标题的图片轮播器
    SDCycleScrollView *cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(10, 0, ScreenWidth-20, 147) delegate:self placeholderImage:[UIImage imageNamed:@"placeholder_big"]];
    [cycleScrollView setBackgroundColor:UIColor.clearColor];
    cycleScrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentCenter;
    cycleScrollView.bannerImageViewContentMode = UIViewContentModeScaleAspectFill;
    cycleScrollView.currentPageDotColor = [UIColor whiteColor];
    cycleScrollView.titleLabelBackgroundColor = [UIColor clearColor];
    //    cycleScrollView.titlesGroup = ({
    //        NSMutableArray *titleArrayM = [NSMutableArray array];
    //        for (int i = 0; i < _headerArr.count; i++) {
    //            NSDictionary *item = _headerArr[i];
    //            [titleArrayM addObject:item[@"title"]];
    //        }
    //
    //        titleArrayM;
    //    });
    
    cycleScrollView.imageURLStringsGroup = ({
        NSMutableArray *urlArrayM = [NSMutableArray array];
        for (int i = 0; i < _headerArr.count; i++) {
            BannerEntity *item = _headerArr[i];
            [urlArrayM addObject:item.image_url];
        }

        urlArrayM;
    });
    
    return cycleScrollView;
}

/** SDCycleScrollView轮播点击事件代理 */
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    NSDictionary *item = _headerArr[index];
    NSLog(@"%@",item);
    //    [((AppDelegate*)[UIApplication sharedApplication].delegate) openNewPage:item[@"exUrl"]];
}


/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
